<template>
    <div class="map">
        <div class="addressShadow-search">
            <input type="text" placeholder="请输入关键字" v-model="mapSearch" id="tipInput" autocomplete="off" v-if="publicData.searchInput">
            <div class="search-close" @click="closeSearch" v-show="mapSearch"></div>
            <button v-if="publicData.searchInput"><span>搜索</span></button>
        </div>
        <div id="container"></div>
    </div>

</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader"

export default {
    name:"serviceMap",
    props:["publicData"],
    data() {
        return{
            key : "ef7824632fe97750c6442a705ec5cc25", //我个人的key,以后或许需要更换成企业的key,
            map: {}, //准备接收map实例
            mapSearch : "", //搜索框文本
            formData : {}, //需要的数据
        }
    },
    mounted(){
        this.getUserLnglat(this.longitude,this.latitude);
    },
    methods:{
        closeSearch(){
            this.mapSearch = "";
        },
        // 获取用户的经纬度
        getUserLnglat(lng,lat){
            let ns = this

            if(lng && lat){
                // console.log("触发了一次有lnglat")
                // ns.$emit("mapLoading");
                ns.initMap(ns,lng,lat);
                return;
            }

            AMapLoader.load({
                key : ns.key,
                version : "1.4.15"
            }).then(() => {
            AMap.plugin('AMap.Geolocation', function() {
                var geolocation = new AMap.Geolocation({
                    // 是否使用高精度定位，默认：true
                    enableHighAccuracy: true,
                    // 设置定位超时时间，默认：无穷大
                    timeout: 5000,
                    // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                    buttonOffset: new AMap.Pixel(10, 20),
                    //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    zoomToAccuracy: true,     
                    //  定位按钮的排放位置,  RB表示右下
                    buttonPosition: 'RB'
                })
                
                geolocation.getCurrentPosition()
                AMap.event.addListener(geolocation, 'complete', onComplete)
                AMap.event.addListener(geolocation, 'error', onError)

                function onComplete (res) {
                    // data是具体的定位信息
                    console.log("成功的回调",res)
                    // console.log(res.position,res.position)
                    let lng = res.position.lng; // 经度
                    let lat = res.position.lat; // 纬度
                    ns.initMap(ns,lng,lat)
                }

                function onError (res) {
                    // 定位出错
                    console.log("失败的回调",res)
                    // ns.initMap(ns,lng,lat)
                    ns.getUserLnglat_html5(ns);
                }
            });
            })


        },
        // 进行地图的初始化
        /**
         * ns:this对象
         * lng:经度 默认"114.504259"
         * lat:纬度 默认"38.046406"
         * 默认经纬度指向石家庄市
         */
        initMap(ns,lng="114.504259",lat="38.046406"){
            AMapLoader.load({
                key : ns.key,
                version : "1.4.15",
                // 地图需要使用的插件列表
                plugins : [
                    "AMap.Geocoder",
                    "AMap.Autocomplete",
                    "AMap.PlaceSearch"
                ],
            }).then(() => {
                console.log(AMap);
                console.log(lng,lat)
                ns.map = new AMap.Map('container',{
                    zoom:17,
                    center:[lng,lat],
                });
                // 准备一个变量接收地址
                let addr = "";
                // 逆地址查询,通过经纬度查询地址信息
                AMap.plugin("AMap.Geocoder",()=>{
                    let geocoder = new AMap.Geocoder();
                    let lnglat = new AMap.LngLat(lng,lat);
                    geocoder.getAddress(lnglat,function(status,res){
                        console.log(`status:${status}`);
                        console.log(res);
                        addr = res.regeocode.addressComponent.street
                        console.log(addr)
                        // 自定义marker样式
                        let content = `
                        <div class="marker">
                            <div class="marker-main">
                            </div>
                        </div>
                        `
                        // 添加marker
                        let marker = new AMap.Marker({
                            content,
                            offset: new AMap.Pixel(-15,-50), // 标记的偏移量
                            location:new AMap.LngLat(lng,lat),
                            title:"当前位置"
                        });
                        // 为marker添加文字框
                        marker.setLabel({
                            offset: new AMap.Pixel(-35, 30),  //设置文本标注偏移量
                            content: `<div class='info' style="border:0; ">
                            我在 <span style="font-weight: 600;">${addr}</span> 附近>
                            </div>`, //设置文本标注内容
                            direction: 'top' //设置文本标注方位
                        });
                        ns.map.add(marker);
                        ns.map.on("click",(e)=>{
                            console.log(e);
                            let lat = e.lnglat.lat;
                            let lng = e.lnglat.lng;
                            let key="cd2fc790adcc324bba183dac6ccf3f43";
                            // 逆地址查询,查询当前点击的坐标的文字描述信息
                            let url =`https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${key}`;
                            ns.axios.get(url).then(res=>{
                            console.log("res",res)
                            // 下面是给准备传父组件的数据赋值
                            ns.formData.preAddr = res.data.regeocode.formatted_address;
                            ns.formData.longitude = lng+"";
                            ns.formData.latitude = lat+"";
                            console.log(res);
                            ns.formData.provinceCode = res.data.regeocode.addressComponent.adcode.slice(0,2);
                            ns.formData.cityCode = res.data.regeocode.addressComponent.adcode.slice(0,4);
                            ns.formData.areaCode = res.data.regeocode.addressComponent.adcode;
                            ns.formData.areaName = res.data.regeocode.addressComponent.district;
                            ns.formData.cityName = res.data.regeocode.addressComponent.city;
                            ns.formData.provinceName = res.data.regeocode.addressComponent.province;
                            console.log(ns.formData.provinceCode,ns.formData.cityCode,ns.formData.areaCode)
                            console.log(ns.formData.latitude,ns.formData.longitude)
                            console.log(ns.formData.preAddr)
                            // 把经纬度渲染上map中
                            ns.getUserLnglat(ns.formData.longitude,ns.formData.latitude);
                            ns.$emit("closeMap",ns.formData)
                            })
                        })
                    })
                })

                AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
                    // let marker = new AMap.marker()
                    // marker.on("click",e=>{
                    //     console.log(e);
                    // })
                    // ns.map.add(marker);
                    var autoOptions = {
                        // 城市，默认全国 
                        city: "全国",
                        // 使用联想输入的input的id
                        input: "tipInput"
                    }
                    var autocomplete= new AMap.Autocomplete(autoOptions)

                    var placeSearch = new AMap.PlaceSearch({
                        city:'全国',
                        map:ns.map
                    })
                    AMap.event.addListener(autocomplete, 'change', function(e){
                        //TODO 针对选中的poi实现自己的功能
                        console.log(e);
                        placeSearch.search(e.poi.name)
                    })
                    AMap.event.addListener(autocomplete, 'select', function(e){
                        //TODO 针对选中的poi实现自己的功能
                        console.log(e);
                        placeSearch.search(e.poi.name)
                    })
                    // 搜索后的marker的点击事件
                    AMap.event.addListener(placeSearch, 'markerClick', function(e){
                        console.log(e);
                        let lng = e.data.location.lng;
                        let lat = e.data.location.lat;
                        // ns.pushData(ns,e,lng,lat);
                        // 下面是给准备传父组件的数据赋值
                        ns.formData.preAddr = e.data.pname + e.data.cityname + e.data.adname + e.data.name;
                        ns.formData.longitude = lng+"";
                        ns.formData.latitude = lat+"";
                        ns.formData.provinceCode = e.data.adcode.slice(0,2);
                        ns.formData.cityCode = e.data.adcode.slice(0,4);
                        ns.formData.areaCode = e.data.adcode;
                        ns.formData.areaName = e.data.adname;
                        ns.formData.cityName = e.data.cityname;
                        ns.formData.provinceName = e.data.pname;
                        console.log(ns.formData.provinceCode,ns.formData.cityCode,ns.formData.areaCode)
                        console.log(ns.formData.latitude,ns.formData.longitude)
                        console.log(ns.formData.address)
                        // 把经纬度渲染上map中
                        ns.getUserLnglat(ns.formData.longitude,ns.formData.latitude);
                        ns.$emit("closeMap",ns.formData)
                    })
                })
            }).catch( err =>{
                console.log(err)
            } )
            
        },
        // 原生h5获得经纬度方法
        getUserLnglat_html5(ns){
            let gl = window.navigator.geolocation;
            gl.getCurrentPosition(function(res){ // 成功的回调
                console.log(res);
                let lng = res.coords.longitude; // 经度
                let lat = res.coords.latitude; // 纬度
                // console.log("触发了一次成功回调")
                // ns.$emit("mapLoading");
                ns.initMap(ns,lng,lat)
            },function(err){ //失败的回调
                console.log(err);
                // console.log("触发了一次失败回调")
                // ns.$emit("mapLoading");
                ns.initMap(ns);
            },{
                timeout: 5000 // 配置项,5秒超时
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.map{
    width: 100% !important;
    height: 100% !important;
    position: relative;
    #container{
        width: 100%;
        height: 100%;
    }
}
.addressShadow-search{
        position: absolute;
        top: 26px;
        left: 40px;
        display: flex;
        z-index: 99999;
        > input{
          border: 0;
          border-radius: 0;
          width: 368px;
          height: 40px;
          background: #FFFFFF;
          font-size: 16px;
          box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.25);
          outline:none;
          text-indent: 14px;
          font-family: "SourceHanSansSC-Regular";
        }
        > button{
          border: 0;
          width: 77px;
          height: 40px;
          background: #045DB9;
          box-shadow: 2px 2px 4px 0px rgba(0,0,0,0.25);
          color: #fff;
          font-size: 16px;
          cursor: pointer;
          > span{
            width: 32px;
            height: 24px;
            font-family: "SourceHanSansSC-Regular";
            font-size: 16px;
            color: #FFFFFF;
            text-align: center;
            font-weight: 400;
          }
        }
        .search-close{
          width: 20px;
          height: 20px;
          background: url("../../../assets/image/service/searchClose.png") no-repeat center;
          position: absolute;
          top: 9px;
          right: 89px;
          cursor: pointer;
        }
      }
</style>

<style lang="scss">
.map{
  .amap-sug-result {
    margin-top: 12px !important;
    z-index: 99999 !important;
  }
  .auto-item{
    font-size: 16px;
    font-family: "SourceHanSansSC-Regular";
    padding: 12px 14px;
    width: 368px;
    border-bottom: 1px solid #efefef;
    text-overflow: ellipsis;
  }
  /* 地图搜索中的灰字以及地图的marker不显示 */
  .auto-item .auto-item-span{
    display: none;
  }
  .marker{
    width: 30px;
    height: 30px;
    border: 1px solid #1d8eff;
    border-radius: 50%;
    background-color: transparent;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .marker-main{
      width: 15px;
      height: 15px;
      background-color: #1d8eff;
      border-radius: 50%;
  }
  .amap-marker-label{
    border: 0 !important;
    font-size: 16px !important;
    padding: 10px 15px !important;
    box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.25) !important;
  }
}
</style>